<template>
	<view>
		<u-navbar back-text="授权登录" :border-bottom="false" :back-text-style="textStyle" back-icon-color="#000000"
			style="font-weight: bold;font-family: PingFang SC;"></u-navbar>

		<!-- APP登录 -->
		<view v-if="millType == 1">
			<!-- 标题 -->
			<view class="typeface1" style="text-align: center;margin-top: 124rpx;">登录注册</view>
			<view style="margin-top: 140rpx;">
				<!-- 手机号 -->
				<view style="border-bottom:1px solid #F1F1F1;margin: 23rpx 102rpx 0rpx 104rpx;">
					<u-row>
						<u-col :span="1">
							<!-- <image src="../../static/img/login_icon_account.png" style="width: 40rpx;height: 40rpx;"></image> -->
						</u-col>
						<u-col :span="11">
							<u-input v-model="phone" type="number" placeholder="请输入手机号" />
						</u-col>
					</u-row>
				</view>
				<!-- 验证码 -->
				<view style="border-bottom:1px solid #F1F1F1;margin: 23rpx 102rpx 0rpx 104rpx;margin-top: 60rpx;">
					<u-row>
						<u-col :span="1">
							<!-- <image src="../../static/img/login_icon_validation.png" style="width: 40rpx;height: 40rpx;"></image> -->
						</u-col>
						<u-col :span="7">
							<u-input v-model="otpCode" type="number" placeholder="请输入验证码" />
						</u-col>
						<u-col :span="4">
							<text @click="codeClick" class="authCode" v-if="changess">验证码</text>
							<text v-else class="authCodes">{{ this.second }} s</text>
						</u-col>
					</u-row>
				</view>
			</view>

			<view class="login" @click="register">登录</view>

			<view @click="handleThirdLoginApp">
				<view class="typeface2" style="text-align: center;margin-top: 100rpx;">第三方授权登录</view>
				<!-- <image src="../../static/img/logo_icon_weic@3x.png" style="width: 90rpx;height: 90rpx;margin-left: 330rpx;margin-top: 40rpx;"></image> -->
				<view class="typeface3" style="text-align: center;margin-top:10rpx;">微信</view>
			</view>

			<view style="text-align: center;margin-top: 130rpx;">
				<u-checkbox v-model="checked" active-color="#333333" style="vertical-align:text-bottom;"></u-checkbox>
				<text class="typeface4">登陆既代表您同意网站的</text>
				<text class="typeface5" @click="goServiceConditions(true)">使用条件</text>
				<text class="typeface4">及</text>
				<text class="typeface5" @click="goServiceConditions(true)">隐私声明</text>
			</view>
		</view>

		<!-- 微信小程序授权登录 -->
		<view v-else>
			<view>
				<view class="header">
					<image src="https://beedao.oss-cn-beijing.aliyuncs.com/afb5981137704e6a80470e12605e0f6c.png">
					</image>
				</view>
				<view class="content">
					<view>申请获取以下权限</view>
					<text>获得你的公开信息(昵称，头像、地区等)</text>
				</view>

				<button class="bottom" v-if="!isPhone" style="background-color: #FCA800;color: #fff;" type="primary"
					open-type="getUserInfo" withCredentials="true" lang="zh_CN" @click="wxGetUserInfo">
					授权登录
				</button>
				<!-- <button v-if="isPhone" class='bottom' style="background-color: #FCA800;color: #fff;" type='primary'
				 open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" lang="zh_CN" withCredentials="true">获取手机号码</button> -->
			</view>
		</view>

		<u-toast ref="uToast" />
	</view>
</template>

<script>
	var that;
	export default {
		data() {
			return {
				millType: uni.getStorageSync('millType'),
				//APP登录
				checked: false,
				currentPhone: null, //当前手机号
				phone: null, //手机号
				otpCode: null, //验证码

				//倒计时
				showText: true,
				second: 59,
				disabled: false,
				changess: true,

				//微信小程序
				SessionKey: '',
				OpenId: '',
				name: null,
				img: null,
				sex: 1,
				code: null,
				encryptedData: null,
				iv: null,
				isPhone: false,
				scene: uni.getStorageSync('scene'),
				isCanUse: uni.getStorageSync('isCanUse') || true, //默认为true
				share_id: '',
				clicklogin: true,
				jumpType: 0,
				jumpParam: {},
				groupType: "", //拼团类型
				orderId: "", //拼团id
			};
		},
		onLoad(option) {
			that = this;
			var parentId = uni.getStorageSync('parentId');
			if (option.id) {
				this.share_id = option.id;
				this.jumpType = option.jumpType;
				this.jumpParam = {
					enterpriseId: option.enterpriseId,
					hotId: option.hotId,
					packageBusinessId: option.packageBusinessId,
					employeeId: option.employeeId,
					redirectId: option.redirectId,
					addType: option.addType,
					types: option.types,
					imgs: option.imgs,
					businessId: option.businessId,
				};
			} else if (option.jumpType) {
				this.jumpType = option.jumpType;
				if (option.groupType) {
					this.groupType = option.groupType;
					this.orderId = option.orderId;
				}
			}
			if (parentId) {
				this.share_id = parentId;
				uni.clearStorageSync('parentId');
			}
			if (uni.getStorageSync('millType') != 1) {
				this.login();
			}
		},
		methods: {
			//微信小程序
			//第一授权获取用户信息===》按钮触发
			wxGetUserInfo() {
				if (that.clicklogin == true) {
					that.clicklogin = false;
					let _this = this;
					try {
						uni.getUserProfile({
							desc: '登录',
							// provider: 'weixin',
							success: function(infoRes) {
								_this.clicklogin = true;
								_this.name = infoRes.userInfo.nickName; //昵称
								_this.img = infoRes.userInfo.avatarUrl; //头像
								_this.sex = infoRes.userInfo.gender; //头像
								_this.encryptedData = infoRes.encryptedData;
								_this.iv = infoRes.iv;
								try {
									uni.setStorageSync('isCanUse', false); //记录是否第一次授权  false:表示不是第一次授权
									_this.updateUserInfo();
								} catch (e) {}
							},
							fail(res) {
								_this.clicklogin = true;
							}
						});
					} catch (e) {
						//  老版
						//进入未授权 -- wx.getUserInfo获取用户信息 
						wx.getUserInfo({
							withCredentials: true,
							success: function(infoRes) {
								console.log(infoRes)
								_this.clicklogin = true;
								_this.name = infoRes.userInfo.nickName; //昵称
								_this.img = infoRes.userInfo.avatarUrl; //头像
								_this.sex = infoRes.userInfo.gender; //头像
								_this.encryptedData = infoRes.encryptedData;
								_this.iv = infoRes.iv;
								try {
									uni.setStorageSync('isCanUse', false); //记录是否第一次授权  false:表示不是第一次授权
									_this.updateUserInfo();
								} catch (e) {}
							},
							fail(res) {
								_this.clicklogin = true;
							}
						})
					}
				} else {
					uni.showToast({
						icon: 'none',
						title: '请不要频繁点击'
					});
				}
			},

			//登录
			login() {
				let _this = this;
				// 1.wx获取登录用户code
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						_this.code = loginRes.code;
						if (!_this.isCanUse) {
							//非第一次授权获取用户信息
							uni.getUserInfo({
								provider: 'weixin',
								success: function(infoRes) {
									//获取用户信息后向调用信息更新方法
									_this.name = infoRes.userInfo.nickName; //昵称
									_this.img = infoRes.userInfo.avatarUrl; //头像
									_this.updateUserInfo(); //调用更新信息方法
								}
							});
						}
					}
				});
			},
			//向后台更新信息
			updateUserInfo() {
				let opts = {
					way: true, //true JSON请求；false 表单请求
					method: 'post',
					url: 'user/authorization/login'
				};
				let data = {
					code: this.code,
					nickName: this.name,
					portrait: this.img,
					sex: this.sex,
					// scene:this.scene,
					encryptedData: this.encryptedData,
					iv: this.iv,
					parentId: this.share_id
				};
				this.http.httpTokenRequest(opts, data).then(res => {
					//打印请求返回的数据
					let data = res.data;
					if (res.code == 200) {
						this.$refs.uToast.show({
							title: res.message,
							type: 'success'
						});
						uni.setStorageSync('token', data.token);
						uni.setStorageSync('userinfo', JSON.stringify(data));
						uni.setStorageSync('isBindPhone', data.isBindPhone == 0 ? false : true);
						this.goPage();

					} else {
						console.log( res)
						that.clicklogin = true;
						this.$refs.uToast.show({
							title: data.message,
							type: 'error'
						});
					}
				});
			},
			// 判断登陆成功后的跳转页面
			goPage() {
				switch (this.jumpType) {
					case '0':
						//没有父级id去首页
						uni.reLaunch({
							url: '../home/home'
						});
						break;
					case '1':
						//首页分享
						uni.reLaunch({
							url: '../home/home'
						});
						break;
					case '2':
						//服务页分享
						uni.reLaunch({
							url: '../service/service'
						});
						break;
					case '3':
						//活动页分享
						uni.reLaunch({
							url: '../activity/activity'
						});
						break;
					case '4':
						//我的页面分享
						uni.reLaunch({
							url: '../personal/personal'
						});
						break;
					case '5':
						//商家主页页面分享
						uni.reLaunch({
							url: '../home/home?type=' + 1 + '&enterpriseId=' + this.jumpParam.enterpriseId +
								'&hotId=' + this.jumpParam.hotId
						});
						break;
					case '6':
						//团购详情分享
						uni.reLaunch({
							url: '../home/home?type=' + 2 + '&enterpriseId=' + this.jumpParam.enterpriseId +
								'&packageBusinessId=' + this.jumpParam.packageBusinessId
						});
						break;
					case '7':
						//他的简历分享
						uni.reLaunch({
							url: '../home/home?type=' + 3 + '&employeeId=' + this.jumpParam.employeeId +
								'&redirectId=' + this.jumpParam.redirectId +
								'&addType=' + this.jumpParam.addType + '&type=' + this.jumpParam.types + '&imgs=' +
								this.jumpParam.imgs
						});
						break;
					case '8':
						// 按次预约下单
						uni.reLaunch({
							url: '../home/home?type=' + 4 + '&businessId=' + this.jumpParam.businessId
						});
						break;
					case '9':
						//营销团长分享
						uni.reLaunch({
							url: '../home/home?type=' + 5
						});
						break;
					case '10':
						//参团分享
						uni.reLaunch({
							url: "/pageageA/placeOrder/appointment?groupType=" + this.groupType + "&orderId=" +
								this.orderId
						});
						break;
					default:
						//没有父级id去首页
						uni.reLaunch({
							url: '../home/home'
						});
						break;
				}
			},
			//绑定手机号事件
			getPhoneNumber(e) {
				var _this = this;
				if (e.detail.errMsg == 'getPhoneNumber:ok') {
					uni.login({
						provider: 'weixin',
						success: function(loginRes) {
							var code = loginRes.code;
							let opts = {
								way: true, //true JSON请求；false 表单请求
								method: 'post',
								url: 'user/bind/phone'
							};
							let data = {
								encryptedData: e.detail.encryptedData,
								iv: e.detail.iv,
								code: code
							};
							_this.http.httpTokenRequest(opts, data).then(res => {
								//打印请求返回的数据
								if (res.code == 200) {
									uni.showToast({
										icon: 'none',
										title: '绑定手机号成功',
										duration: 1500
									});
									uni.setStorageSync('isBindPhone', true);
									uni.reLaunch({
										url: '../home/home'
									});
								} else {
									this.$refs.uToast.show({
										title: res.message,
										type: 'error'
									});
								}
							});
						}
					});
				} else {}
			},

			//app登录
			handleThirdLoginApp() {
				let falg = true;
				if (!this.checked) {
					this.$refs.uToast.show({
						title: '请勾选协议',
						type: 'default'
					});
					return (falg = false);
				}

				var that = this;
				if (falg) {
					uni.getProvider({
						service: 'oauth',
						success: function(res) {
							//支持微信、qq和微博等
							if (~res.provider.indexOf('weixin')) {
								uni.login({
									provider: 'weixin',

									success: function(loginRes) {
										that.getApploginData(loginRes); //请求登录接口方法
									},
									fail: function(res) {
										console.log('App微信获取用户信息失败', res);
									}
								});
							}
						}
					});
				}
			},

			//请求登录接口方法

			getApploginData(data) {
				var that = this;
				//这边是前端自己去调微信用户信息的接口，根据接口需要请求，如果不需要前端去获取的话就交给后端，可省去次操作
				uni.request({
					url: 'https://api.weixin.qq.com/sns/userinfo?access_token=' + data.authResult.access_token +
						'&openid=' + data.authResult.openid,
					method: 'GET',
					dataType: 'json',
					header: {
						'content-type': 'application/x-www-form-urlencoded' // 默认值
					},
					success(res) {
						var wxData = res;
						let opts = {
							way: true, //true JSON请求；false 表单请求
							method: 'post',
							url: 'login/wxLogin'
						};
						let Data = {
							unionId: wxData.data.unionid
						};
						that.http.httpTokenRequest(opts, Data).then(res => {
							//打印请求返回的数据
							let data = res.data;

							if (res.code == '200') {
								that.$refs.uToast.show({
									title: data.message,
									type: 'success'
								});
								uni.setStorageSync('token', data.data);
								uni.reLaunch({
									url: '../home/home'
								});
								// this.personalInformation();
							} else if (data.code == '1013') {
								that.$refs.uToast.show({
									title: data.message,
									type: 'message'
								});
								let json = {
									nickname: wxData.data.nickname,
									sex: wxData.data.sex,
									headimgurl: wxData.data.headimgurl,
									unionid: wxData.data.unionid
								};
								uni.navigateTo({
									url: './bindPhone/bindPhone?json=' + JSON.stringify(json)
								});
							} else {
								that.$refs.uToast.show({
									title: data.message,
									type: 'message'
								});
							}
						});
					},
					fail() {}
				});
			},
			//获取个人信息
			personalInformation: function() {
				let opts = {
					way: true, //true JSON请求；false 表单请求
					method: 'post',
					url: 'User/findById'
				};

				let data = {};

				this.http.httpTokenRequest(opts, data).then(res => {
					//打印请求返回的数据
					let data = JSON.parse(res.data);
					if (data.code == '200') {
						// this.userinfo=data.data;
						// this.isVip=data.data.isVip;
						uni.setStorageSync('isVip', this.isVip);
						uni.setStorageSync('userinfo', JSON.stringify(this.userinfo));
					} else {
						uni.showToast({
							title: data.message,
							icon: 'none',
							duration: 2000
						});
					}
				});
			},
			//跳转协议
			goServiceConditions: function(type) {
				if (type) {
					// this.modelUrl+'privacyStatement.html'
					//使用条件
					uni.navigateTo({
						url: './serviceConditions?url=' + 'https://www.cnblogs.com/yangyang520/p/11611384.html'
					});
				} else {
					uni.navigateTo({
						url: './serviceConditions?url=' + 'https://www.cnblogs.com/yangyang520/p/11611384.html'
					});
				}
			},
			codeClick: function() {
				let falg = true;

				if (!this.phone) {
					this.$refs.uToast.show({
						title: '请输入手机号',
						type: 'default'
					});
					return (falg = false);
				}

				if (this.phone.length != 11) {
					this.$refs.uToast.show({
						title: '请输入正确手机号',
						type: 'default'
					});
					return (falg = false);
				}
				if (falg) {
					let opts = {
						way: true, //true JSON请求；false 表单请求
						method: 'post',
						url: 'login/sendSms'
					};
					let data = {
						phone: this.phone
					};
					this.http.httpTokenRequest(opts, data).then(res => {
						//打印请求返回的数据
						let data = JSON.parse(res.data);
						if (data.code == '000000') {
							this.$refs.uToast.show({
								title: data.message,
								type: 'success'
							});
							this.changess = false;
							this.disabled = true;
							this.showText = false;
							var interval = setInterval(() => {
								--this.second;
							}, 1000);

							setTimeout(() => {
								clearInterval(interval);
								this.showText = true;
								this.second = 59;
								this.disabled = false;
								this.changess = true;
							}, 60000);
						} else {
							this.$refs.uToast.show({
								title: data.message,
								type: 'message'
							});
						}
					});
				}
			},
			//登录
			register: function() {
				let falg = true;

				if (!this.phone) {
					this.$refs.uToast.show({
						title: '请输入手机号',
						type: 'default'
					});
					return (falg = false);
				}

				if (this.phone.length != 11) {
					this.$refs.uToast.show({
						title: '请输入正确手机号',
						type: 'default'
					});
					return (falg = false);
				}

				if (!this.otpCode) {
					this.$refs.uToast.show({
						title: '请输入验证码',
						type: 'default'
					});
					return (falg = false);
				}
				if (!this.checked) {
					this.$refs.uToast.show({
						title: '请勾选协议',
						type: 'default'
					});
					return (falg = false);
				}
				if (falg) {
					let opts = {
						way: true, //true JSON请求；false 表单请求
						method: 'post',
						url: 'login/smsLogin'
					};
					let data = {
						phone: this.phone,
						phoneCode: this.otpCode
					};

					this.http.httpTokenRequest(opts, data).then(res => {
						//打印请求返回的数据
						let data = JSON.parse(res.data);
						if (data.code == 200) {
							this.$refs.uToast.show({
								title: data.message,
								type: 'success'
							});
							uni.setStorageSync('token', data.data);
							uni.reLaunch({
								url: '../home/home'
							});
						} else {
							this.$refs.uToast.show({
								title: data.message,
								type: 'error'
							});
						}
					});
				}
			}
		}
	};
</script>

<style>
	.typeface1 {
		font-size: 40rpx;
		font-family: PingFang SC;
		font-weight: bold;
		color: #11934a;
		opacity: 1;
	}

	.typeface2 {
		font-size: 24rpx;
		font-family: PingFang SC;
		font-weight: 400;
		color: #cccccc;
		opacity: 1;
	}

	.typeface3 {
		font-size: 28rpx;
		font-family: PingFang SC;
		font-weight: 400;
		color: #666666;
		opacity: 1;
	}

	.typeface4 {
		font-size: 28rpx;
		font-family: PingFang SC Regular;
		font-weight: 400;
		color: #333333;
		opacity: 1;
	}

	.typeface5 {
		font-size: 28rpx;
		font-family: PingFang SC Regular;
		font-weight: 400;
		color: #f1244f;
		opacity: 1;
	}

	.login {
		margin-left: 116rpx;
		margin-top: 176rpx;
		width: 520rpx;
		height: 88rpx;
		background: #07bd44;
		opacity: 1;
		border-radius: 10rpx;
		text-align: center;
		line-height: 88rpx;
		font-size: 36rpx;
		font-family: PingFang SC;
		font-weight: 400;
		color: #ffffff;
		opacity: 1;
	}

	.authCode {
		color: #07bd44;
		font-size: 28rpx;
		font-family: PingFang SC;
		font-weight: bold;
		background-color: #f8f8f8;
		padding: 20rpx 30rpx 20rpx 30rpx;
		border-radius: 15rpx;
	}

	.authCodes {
		color: #ffffff;
		font-size: 28rpx;
		font-family: PingFang SC;
		font-weight: bold;
		background-color: #07bd44;
		padding: 20rpx 30rpx 20rpx 30rpx;
		border-radius: 15rpx;
	}

	/* 小程序获取验证码 */
	.header {
		margin: 90rpx 0 90rpx 50rpx;
		border-bottom: 1px solid #ccc;
		text-align: center;
		width: 650rpx;
		height: 300rpx;
		line-height: 450rpx;
	}

	.header image {
		width: 200rpx;
		height: 200rpx;
	}

	.content {
		margin-left: 50rpx;
		margin-bottom: 90rpx;
	}

	.content text {
		display: block;
		color: #9d9d9d;
		margin-top: 40rpx;
	}

	.bottom {
		border-radius: 80rpx;
		margin: 70rpx 50rpx;
		font-size: 35rpx;
	}
</style>
